from threading import Thread
from selenium import webdriver
import random
import time

def thread_wrapper(func):
    def wraper(*args,**kwargs):
        if args:
            thread = Thread(target=func,args=args)
        elif kwargs:
            thread = Thread(target=func,kwargs=kwargs)
        else:
            thread = Thread(target=func)
        return thread
    return wraper

class Settings():
    executable_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe',


class Driver():
    def __init__(self,st=Settings):
        self.st = st
        self.initialize()

    def get(self,url):
        self.driver.get(url)

    def close(self):
        self.driver.quit()

    def restart(self):
        self.close()
        self.initialize()

    def initialize(self):
        self.driver = webdriver.Chrome(
            executable_path=self.st.executable_path
        )

class CookiePool(Driver):
    def __init__(self,urls):
        self.urls = urls
        self.__cookie_str = ''
        super(CookiePool,self).__init__()

    @thread_wrapper
    def run(self):
        while True:
            url = random.choice(self.urls)
            self.driver.get(url)
            cookies = self.driver.get_cookies()
            name_value = [
                '%s=%s' % (cookie['name'], cookie['value']) for cookie in cookies
            ]
            self.__cookie_str = '; '.join(name_value)
            self.restart()

    def get_cookie(self):
        while not self.__cookie_str:
            time.sleep(1)
            print('第一次没执行完呢，你猴急什么')
        return self.__cookie_str







if __name__ == '__main__':
    # driver = Driver()
    # driver.get('https://blog.csdn.net/kzl_knight/article/details/103181404')
    # driver.close()
    # driver.restart()
    cookiePool = CookiePool(
        urls=[
            'https://blog.csdn.net/kzl_knight/article/details/103187223',
            'https://blog.csdn.net/kzl_knight/article/details/103182569',
        ])
    cookiePool.run().start()
    while True:
        cookie = cookiePool.get_cookie()
        print(cookie)
        time.sleep(1)


